package com.youhong.teethcare;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.jstyle.countrylibrary.CountryPage;
import com.mob.tools.FakeActivity;
import com.youhong.teethcare.netbeans.LoginHttpReturn;
import com.youhong.teethcare.netbeans.LoginServerInterface;
import com.youhong.teethcare.services.Common;
import com.youhong.teethcare.settingpage.DeviceManagerActivity;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.smssdk.SMSSDK;

/*
import com.jstyle.countrylibrary.CountryPage;
import com.mob.tools.FakeActivity;
*/
//import cn.smssdk.SMSSDK;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.login_btn_login)
    Button btn_login;
    //    @BindView(R.id.login_iv_emailPhoneIcon)
//    ImageView iv_emailPhoneIcon;
    @BindView(R.id.login_rg)
    RadioGroup rg;
    @BindView(R.id.login_et_email)
    EditText et_email;
    @BindView(R.id.login_et_password)
    EditText et_password;
    @BindView(R.id.login_tv_rememberPassword)
    TextView tv_rememberPassword;
    @BindView(R.id.login_tv_areaCode)
    TextView tv_areaCode;
    @BindView(R.id.login_tv_forgetPassword)
    TextView tv_forgetPassword;
    @BindView(R.id.login_tv_signUp)
    TextView tv_signUp;
    boolean isRememberPassword = true;
    FrameLayout.LayoutParams frameLayoutParams;

    private static final String TAG = "LoginActivity";
    @BindView(R.id.CheckBox_PsdShow)
    CheckBox CheckBoxPsdShow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                showLoginType(checkedId == R.id.login_rb_email?loginType_Email:loginType_Phone);
                et_email.setText("");
                et_password.setText("");
            }
        });
        showPsd();
    }

    final int loginType_Email = 0;
    final int loginType_Phone = 1;
    int loginType = loginType_Email;

    void showLoginType(int type) {
        loginType=type;
        if (type == loginType_Email) {
            tv_areaCode.setVisibility(View.GONE);
            et_email.setHint(R.string.string_login3);
        } else {
            tv_areaCode.setVisibility(View.VISIBLE);
            et_email.setHint(R.string.string_login4);
        }
    }

    void showPsd() {

        isRememberPassword = Common.userInfo.isRememberPassword();
        String countryCode=Common.userInfo.AreaCode;
        Log.i(TAG, "showPsd: "+countryCode);
        if(TextUtils.isEmpty(countryCode))countryCode="+86";
        tv_areaCode.setText(countryCode);
        int loginType=Common.userInfo.lastLoginType;
        rg.check(loginType==loginType_Email?R.id.login_rb_email:R.id.login_rb_phone);
        showRememberPassword(isRememberPassword);

        if (isRememberPassword) {
            et_email.setText(Common.userInfo.Account);
            et_password.setText(Common.userInfo.Psd);
        }
        CheckBoxPsdShow.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    //设置EditText的密码为可见的
                    et_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    //设置密码为隐藏的
                    et_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
            }
        });
    }

    //当注册成功后，通过该ID通知Login界面直接登录，不需要注册后再次登录了
    public static int REQ_REGISTER = 0xAA3;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == REQ_REGISTER && resultCode == Activity.RESULT_OK) {

            String account = data.getStringExtra("account");
            String password = data.getStringExtra("password");
            login(account, password);

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @OnClick({R.id.login_btn_login, R.id.login_tv_rememberPassword, R.id.login_tv_areaCode
            , R.id.login_tv_forgetPassword, R.id.login_tv_signUp})
    public void onClick(View view) {

        switch (view.getId()) {

            case R.id.login_btn_login: {
                login();
            }
            break;
            case R.id.login_tv_rememberPassword: {
                isRememberPassword = !isRememberPassword;
                showRememberPassword(isRememberPassword);
                Common.userInfo.setRememberPassword(isRememberPassword);
                Common.userInfo.SyncToLocal(this);
            }
            break;
            case R.id.login_tv_areaCode: {
                getCountryCode();
            }
            break;

            case R.id.login_tv_forgetPassword: {

                startActivity(RetrieveActivity.class);
            }
            break;
            case R.id.login_tv_signUp: {
                startActivityForResult(new Intent(this, RegisterActivity.class), REQ_REGISTER);
                overridePendingTransition(R.anim.push_right_in, R.anim.push_left_out);
            }
        }

    }

    void showRememberPassword(boolean isRememberPassword) {
        if (isRememberPassword) {

            Drawable drawable = getResources().getDrawable(R.mipmap.icon_login_checked);
            drawable.setBounds(0, 0, 50, 44);
            tv_rememberPassword.setCompoundDrawables(drawable, null, null, null);
        } else {

            Drawable drawable = getResources().getDrawable(R.mipmap.icon_login_uncheck);
            drawable.setBounds(0, 0, 50, 44);
            tv_rememberPassword.setCompoundDrawables(drawable, null, null, null);

        }
    }

    private void getCountryCode() {

        CountryPage phone = new CountryPage();
        phone.setCountryId("1");
        // Typeface typeface = Typeface.createFromAsset(getAssets(), "SourceHanSansCN-Regular.ttf");
        // phone.setTypeFace(typeface);
        phone.showForResult(this, (Intent) null, new FakeActivity() {
            @Override
            public void onResult(HashMap<String, Object> data) {
                super.onResult(data);
                if (null != data && null != data.get("id")) {
                    String currentId = (String) data.get("id");

                    if (CountryPage.Result_OK == (int) data.get("result")) {
                        String[] res = SMSSDK.getCountry(currentId);
                        tv_areaCode.setText("+" + res[1]);
                        //countryCode = "00" + res[1] + "-";
                    }
                }

            }
        });
    }

    private void login() {

        String account = et_email.getText().toString().trim();
        String pwd = et_password.getText().toString().trim();
        if (TextUtils.isEmpty(account) || TextUtils.isEmpty(pwd)) {
            Toast.makeText(
                    this,
                    getResources()
                            .getString(R.string.string_login11),
                    Toast.LENGTH_SHORT).show();
            return;
        }

        if (rg.getCheckedRadioButtonId() == R.id.login_rb_phone) {
            String counrtyCode = tv_areaCode.getText().toString().replace("+", "00");

            LoginServerInterface.Login(false
                    , counrtyCode + "-" + account, pwd, login_callback);
        } else {

            LoginServerInterface.Login(true
                    , account, pwd, login_callback);
        }


    }

    private void login(String account, String password) {

        LoginServerInterface.Login(account.contains("@")
                , account, password, login_callback);

    }

    public static String showResult(int msgCode, Context context) {
        // TODO Auto-generated method stub
        if (msgCode == 1) {


        } else if (msgCode == 2) {


        } else if (msgCode == 5) {
            return context.getResources().getString(R.string.wrong_parameter);

        } else if (msgCode == 10) {

            return context.getResources().getString(R.string.phone_exists);

        } else if (msgCode == 1013) {

            return context.getResources().getString(R.string.account_or_psd_wrong);

        } else if (msgCode == 1015) {

            return context.getResources().getString(R.string.email_exists);

        } else if (msgCode == 1016) {

            return context.getResources().getString(R.string.email_exists);
        } else if (msgCode == 1012) {

            return context.getResources().getString(R.string.user_does_not_exist);
        }
        /* else if (result.equals("error")) {
            return getResources().getString(R.string.connection_timeout);

        }*/
        else if (msgCode == 1368) {
            return context.getResources().getString(R.string.wrong_verification_code);
        }
        return "UnknowError";
    }

    LoginServerInterface.LoginCallbackInterface login_callback = new LoginServerInterface.LoginCallbackInterface() {
        @Override
        public void callback(final LoginHttpReturn mReturn) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {


                    if (mReturn == null) {

                        Toast.makeText(LoginActivity.this,
                                R.string.strings30, Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (mReturn.getMsgCode() == 1) {

                        //保存用户ID
                        Common.userInfo.setToken(mReturn.getData());
                        Common.userInfo.setLastLoginType(loginType);
                        Common.userInfo.SyncToLocal(getApplicationContext());
                        saveAccountInfo();
                        //Toast.makeText(LoginActivity.this, "Successful", Toast.LENGTH_SHORT).show();

                        startActivity(TextUtils.isEmpty(Common.userInfo.getMac()) ? DeviceManagerActivity.class : MainActivity.class);
                        finish();

                    } else {

                       Toast.makeText(LoginActivity.this, showResult(mReturn.getMsgCode(), LoginActivity.this), Toast.LENGTH_SHORT).show();
                    }

                }
            });
        }
    };

    private void saveAccountInfo() {
        String account = "";
        String psd = "";
        String countryCode="+86";
        if (isRememberPassword) {
            account = et_email.getText().toString();
            psd = et_password.getText().toString();
            countryCode=tv_areaCode.getText().toString();
        }
        Common.userInfo.setAccount(account);
        Common.userInfo.setAreaCode(countryCode);
        Common.userInfo.setPsd(psd);
    }

}
